<?php
/**
 * @package base
 */
require_once "_sitecontext.php";

/**
 * Handling of locale dependent entits.
 * 
 * Price handling:
 * 		in case of pages language set to cs, CZK currency is used by default
 * 		otherwise EUR is used by default
 *
 */
class LocaleManager {
	public static $CURR_MAP = array(
		self::CURR_CZK => "Kč",
		self::CURR_EUR => "EUR"
	);
	const CURR_CZK = "czk";
	const CURR_EUR = "eur";
	
	/**
	 * Specify wheter currency czk or eur is used for a current set language.
	 */
	public static function currentLangToCurrency() {
		switch(SiteContext::getSiteContext()->getSiteLang()->getLang()) {
			case "cs":
				return self::CURR_CZK;
			default:
				return self::CURR_EUR;
		}
	}
	
	/**
	 * Make $value formatted.
	 * E.g. '4500000' -> '4 500 000'
	 * 
	 * @param $value - value to be formatted
	 * @return string - formatted value
	 */
	public static function valueFormatted($value) {
		$value = intval($value);
		$valueArray = array_reverse(str_split(strval($value)));
		$result = "";
		for ($pos = 0; $pos < sizeof($valueArray); ++$pos) {
			if ($pos % 3 == 0 && $pos != 0) {
				$result .= strrev("&nbsp;") . $valueArray[$pos] ;
			} else {
				$result .= $valueArray[$pos];
			}
		}
		return strrev($result);
	}
	
	/**
	 * Formate currencty.
	 * @see LocaleManager::valueFormatted
	 */
	private static function currencyFormatted($value, $curr) {
		return self::valueFormatted($value) . " " . self::$CURR_MAP[$curr];
	}
	
	/**
	 * Get complete string with price and currency depending to
	 * current language.
	 * 
	 * @param string $value - price
	 * @param string $originalCurrency - original currency of the $value
	 * @param string $desiredCurrency - desired currency for the $value
	 */
	static function price(string $value, string $originalCurrency, string $desiredCurrency = null) {
		$valueOfEurInCzk = Settings::getSettings()->eurInCzk;
		
		if (is_null($desiredCurrency)) {
			$desiredCurrency = self::currentLangToCurrency();
		}
		if ($originalCurrency == $desiredCurrency) {
			return self::currencyFormatted($value, $desiredCurrency);
		}
		if ($originalCurrency == self::CURR_CZK && $desiredCurrency == self::CURR_EUR) {
			// to EUR
			return self::currencyFormatted($value / $valueOfEurInCzk, $desiredCurrency);
		}
		if ($originalCurrency == self::CURR_EUR && $desiredCurrency == self::CURR_CZK) {
			// to CZK
			return self::currencyFormatted($value * $valueOfEurInCzk, $desiredCurrency);
		}
		throw new ExceptionIllegalState("Unsupported currency used: $curr.");
	}
}
?>